package com.cat.model.biz.service.api.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alonew.db.dao.TxCommonDAO;
import com.alonew.json.JSONException;
import com.alonew.json.JSONObject;
import com.cat.model.biz.component.alipay.util.AlipayUtil;
import com.cat.model.biz.component.wechat.bean.AppPayReqData;
import com.cat.model.biz.component.wechat.bean.jsPayReqData;
import com.cat.model.biz.component.wechat.contant.WXConstants;
import com.cat.model.biz.logic.OrderLogic;
import com.cat.model.biz.service.api.BasOrderService;
import com.cat.model.common.enumerator.OrderStatus;
import com.cat.model.common.enumerator.SubjectType;
import com.cat.model.common.model.common.BasOrderVO;
import com.cat.model.common.model.common.ModelExtendtimeVO;
import com.cat.model.common.model.common.ModelInfoVO;
import com.cat.model.common.util.ErrorCode;
import com.cat.model.dao.mapper.ModelMapper;
import com.tencent.common.HttpsRequest;
import com.tencent.common.RandomStringGenerator;
import com.tencent.common.Signature;
import com.tencent.common.Util;
import com.tencent.common.XMLParser;

@Service("basOrderService")
public class BasOrderServiceImpl implements BasOrderService{
	@Autowired
	private ModelMapper modelMapper;
	@Autowired
	private OrderLogic orderLogic;
	@Autowired
	private TxCommonDAO txCommonDAO;

	@Override
	public String createModelExtendtimeOrder(long userId,ModelExtendtimeVO extendtime) {
		BasOrderVO refBasOrder = orderLogic.getOrderByNo(extendtime.getRefOrderNumber());
		if(null == refBasOrder){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		
		BasOrderVO basOrder = new BasOrderVO();
		basOrder.setSubjectType(SubjectType.Extend.getValue());
		basOrder.setSubjectId(extendtime.getModelId());
		 ModelInfoVO modelInfo = modelMapper.getModelInfo(extendtime.getModelId());
         if(modelInfo!=null){
        	 basOrder.setSubjectName(modelInfo.getName());
         }
		basOrder.setUserId(userId);
		basOrder.setCreateTime(new Date());
		basOrder.setStatus("01");//01-未付
		basOrder.setTotalAmount(extendtime.getTotalAmount());
		basOrder.setName(refBasOrder.getName());
		basOrder.setPhoneNo(refBasOrder.getPhoneNo());
		basOrder.setAddress(refBasOrder.getAddress());
		basOrder.setRefBizCode("02");//模特加时
		basOrder.setRefBizName("模特加时");
		
		String orderNumber = orderLogic.insertOrderNumber();
		basOrder.setOrderNumber(orderNumber);
		
		extendtime.setOrderNumber(orderNumber);
		txCommonDAO.insert(extendtime);
		
		basOrder.setRefBizId(extendtime.getId());//
		
		txCommonDAO.insert(basOrder);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			infoJson.put("id", basOrder.getId());
			infoJson.put("orderNumber", basOrder.getOrderNumber());
			infoJson.put("userId", basOrder.getUserId());
			if(basOrder.getCreateTime()!=null){
				infoJson.put("createTime", sdf.format(basOrder.getCreateTime()));
			}else {
				infoJson.put("createTime", "");
			}
			infoJson.put("totalAmount", basOrder.getTotalAmount());
			infoJson.put("phoneNo", basOrder.getPhoneNo());
			infoJson.put("name", basOrder.getName());
			infoJson.put("subjectId", basOrder.getSubjectId());
			infoJson.put("subjectType", basOrder.getSubjectType());
			infoJson.put("subjectName", basOrder.getSubjectName());
			infoJson.put("refBizCode", basOrder.getRefBizCode());
			infoJson.put("refBizId", basOrder.getRefBizId());
			infoJson.put("refBizName", basOrder.getRefBizName());
			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}

	@Override
	public String revorkBasOrder(long userId, String refOrderNumber) {
		BasOrderVO refBasOrder = orderLogic.getOrderByNo(refOrderNumber);
		if(null == refBasOrder){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		
		if(!OrderStatus.PAYED.getValue().equals(refBasOrder.getStatus())){
			return ErrorCode.BASORDER_STATUS_ERROR.response();
		}
		
		refBasOrder.setStatus(OrderStatus.REBACKING.getValue());//03-退款中
		
		txCommonDAO.updateById(refBasOrder,"status");
		
		return ErrorCode.OK.response();
	}
	
	
	/**
	 * 根据订单号获取订单详情
	 * @param userId
	 * @param refOrderNumber
	 * @return
	 */
	public String getOrderDetail(long userId, String refOrderNumber){
		
		BasOrderVO basOrder = orderLogic.getOrderByNo(refOrderNumber);
		if(null == basOrder){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		return ErrorCode.OK.response();
	}
	
	/**
	 * 获取订单状态
	 * @param userId
	 * @param refOrderNumber
	 * @return
	 */
	public String getOrderStatus(long userId, String refOrderNumber){
		JSONObject json = ErrorCode.OK.responseJSON();

		BasOrderVO order = orderLogic.getOrderByNo(refOrderNumber);
		if(null == order){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		if(userId != order.getUserId()){
			return ErrorCode.ILLEGAL_OPERATION.response();
		}
		try {
			json.put("data", order.getStatus());
			return json.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return ErrorCode.SERVER_ERROR.response();
		}
		
	}
	
	/**
	 * 根据订单id获取支付宝支付信息
	 * @param userId
	 * @param orderId
	 * @return
	 */
	public String getAliPayInfo(Long userId,String orderNumber){
		JSONObject json = ErrorCode.OK.responseJSON();

		BasOrderVO order = orderLogic.getOrderByNo(orderNumber);
		if(null == order){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		if(userId != order.getUserId()){
			return ErrorCode.ILLEGAL_OPERATION.response();
		}
		String orderInfo=AlipayUtil.getOrderInfo(order.getName(), "支付宝下单", order.getTotalAmount().toString(), order.getOrderNumber());
		
		String sign = AlipayUtil.sign(orderInfo);
		if(sign!=null){
			try {
	            /**
	             * 仅需对sign 做URL编码
	             */
			 sign = URLEncoder.encode(sign, "UTF-8");
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
				return ErrorCode.SERVER_ERROR.response();
	        }
		 /**
	         * 完整的符合支付宝参数规范的订单信息
	         */
	        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + AlipayUtil.getSignType();
	        try {
				json.put("data", payInfo);
				return json.toString();
			} catch (JSONException e) {
				e.printStackTrace();
				return ErrorCode.SERVER_ERROR.response();
			}
		}else{
			return ErrorCode.SIGN_INVALID.response();
		}
		//return ErrorCode.OK.response();

	}
	
	/**
	 * 根据订单id获取微信支付信息
	 * @param userId
	 * @param orderId
	 * @return
	 */
	public String getWXPayInfo(Long userId,String orderNumber){
		JSONObject json = ErrorCode.OK.responseJSON();

		BasOrderVO order = orderLogic.getOrderByNo(orderNumber);
		if(null == order){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		if(userId != order.getUserId()){
			return ErrorCode.ILLEGAL_OPERATION.response();
		}
        Map<String, Object> resultMap = new HashMap<String, Object>();

		AppPayReqData payReqData=new AppPayReqData("APP", "易选模-订单支付", "app下单", order.getOrderNumber(), 
	        		(order.getTotalAmount().multiply(new BigDecimal("100"))).intValue(), null, 
	        		"123.12.12.123", null, this.getTimeExpire(),  WXConstants.WECHAT_NOTIFYURL);
		try {
        	HttpsRequest httpsRequest = new HttpsRequest();
            String result = httpsRequest.sendPost(WXConstants.WECHAT_PAY_URL, payReqData);
            Util.log("微信预支付请求参数:" + payReqData);
            Util.log("微信预支付返回结果:" + result);
            Map<String, Object> returnMap = XMLParser.getMapFromXML(result);
            String returnCode = returnMap.get("return_code").toString();
            if ("SUCCESS".equals(returnCode)) {//判断微信返回状态是否成功
                String resultCode = returnMap.get("result_code").toString();
                if ("SUCCESS".equals(resultCode)) {//再判断微信处理结果是否成功
                	//签名
                    String nonceStr=RandomStringGenerator.getRandomStringByLength(32);
                    String timeStamp=String.valueOf((System.currentTimeMillis() / 1000));
                    //根据API给的签名规则进行签名
                    Map<String, Object> packageParams= new HashMap<String, Object>();
                    packageParams.put("appid", WXConstants.WECHAT_APPID);
                    packageParams.put("partnerid", WXConstants.WECHAT_MCHID);
                    packageParams.put("prepayid", returnMap.get("prepay_id"));
                    packageParams.put("package", "Sign=WXPay");
                    packageParams.put("noncestr", nonceStr);
                    packageParams.put("timestamp", timeStamp);
                    String paySign = Signature.getSign(packageParams);
                    resultMap.put("sign", paySign);
                    resultMap.put("appid", WXConstants.WECHAT_APPID);
                    resultMap.put("prepayid", returnMap.get("prepay_id"));
                    resultMap.put("nonceStr",nonceStr);
                    resultMap.put("timeStamp", timeStamp);
                    resultMap.put("package", "Sign=WXPay");
                    resultMap.put("partnerid", WXConstants.WECHAT_MCHID);
                } else {
                    resultMap.put("msg", returnMap.get("err_code_des"));
                }
            } else {
                resultMap.put("msg", returnMap.get("return_msg"));
            }
            try {
				json.put("data", resultMap);
				return json.toString();
			} catch (JSONException e) {
				e.printStackTrace();
				return ErrorCode.SERVER_ERROR.response();
			}
        }catch (Exception e) {
            e.printStackTrace();
			return ErrorCode.SERVER_ERROR.response();

        }
	}
	
	public String getPrePayInfo(Long userId,String orderNumber){
		
		
		JSONObject json = ErrorCode.OK.responseJSON();

		BasOrderVO order = orderLogic.getOrderByNo(orderNumber);
		if(null == order){
			return ErrorCode.ORDERNUM_NOFOUND_ERROR.response();
		}
		if(userId != order.getUserId()){
			return ErrorCode.ILLEGAL_OPERATION.response();
		}
		jsPayReqData payReqData=new jsPayReqData("APP", "易选模-订单支付", "app下单", order.getOrderNumber(), 
	        		(order.getTotalAmount().multiply(new BigDecimal("100"))).intValue(), null, 
	        		"123.12.12.123", null, this.getTimeExpire(),  WXConstants.WECHAT_NOTIFYURL);
		
		
		
		
		
		
		try {
			json.put("data", payReqData);
			return json.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return ErrorCode.SERVER_ERROR.response();
		}
		
	}
	
    /**
     * 生成订单失效时间字符串
     * @return
     */
    public String getTimeExpire() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR_OF_DAY, 24);
        return DateFormatUtils.format(calendar.getTime(), "yyyyMMddHHmmss");
    }
}
